import { useEffect, useState } from 'react';
import { Modal, Tabs, Input, Tree, Transfer, App } from 'antd';
import { getElementsTree } from '@/api/element';
import { getRolePermission, saveRolePermission, getRoleElement, saveRoleElements } from '@/api/role';
import { getDictByCode } from '@/api/dict';

const { Search } = Input;

const RolePermissionConfig = ({ visible, roleId, onCancel, onConfirm }) => {
  const { message } = App.useApp();
  const [activeTab, setActiveTab] = useState('elements');
  const [filterText, setFilterText] = useState('');
  const [treeData, setTreeData] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState({
    checked: [],
    halfChecked: []
  });
  const [expandedKeys, setExpandedKeys] = useState([]); // 添加展开节点状态
  const [autoExpandParent, setAutoExpandParent] = useState(true); // 控制是否自动展开父节点
  const [allApi, setAllApi] = useState([]);
  const [roleApi, setRoleApi] = useState([]);

  // 获取角色页面元素权限
  const searchRoleElements = (currentTreeData) => {
    if (!roleId) return;
    getRoleElement(roleId).then(res => {
      const checkedNodeIds = res.data || [];
      // 计算半选状态节点
      const { checked, halfChecked } = calculateCheckedState(checkedNodeIds, currentTreeData || treeData);
      const data = {
        checked,
        halfChecked
      }
      setCheckedKeys(data || []);
    });
  };

  // 获取角色接口权限
  const searchRoleApis = () => {
    if (!roleId) return;
    getRolePermission(roleId).then(res => {
      setRoleApi(res.data || []);
    });
  };

  const loadData = async () => {
    const [elementsRes, dictRes] = await Promise.all([
      getElementsTree(),
      getDictByCode('admin', { dictCode: 'allApi' })
    ]);
    // 设置元素数据
    setTreeData(elementsRes.data || []);
    // 当treeData更新后再调用searchRoleElements
    searchRoleElements(elementsRes.data || []);
    // 设置接口数据
    const apis = (dictRes.data?.others || []).map(item => ({
      key: item.value,
      title: item.label
    }));
    setAllApi(apis);
  };

  useEffect(() => {
    if (visible) {
      loadData();
      if (activeTab === 'api') {
        searchRoleApis();
      }
    }
  }, [visible, activeTab, roleId]);

  const handleTabChange = (key) => {
    setActiveTab(key);
    if (key === 'elements') {
      searchRoleElements();
    } else if (key === 'api') {
      searchRoleApis();
    }
  };

  const handleSearch = (e) => {
    const { value } = e.target;
    setFilterText(value);
    
    // 根据搜索文本更新展开的节点
    if (value) {
      // 查找所有匹配的节点及其父节点
      const expandKeys = getAllMatchedKeys(value, treeData);
      setExpandedKeys(expandKeys);
      setAutoExpandParent(true);
    } else {
      // 如果搜索文本为空，清空展开的节点
      setExpandedKeys([]);
    }
  };

  // 获取所有匹配节点的key（包括父节点）
  const getAllMatchedKeys = (searchText, treeNodes) => {
    const matchedKeys = [];
    const expandKeys = [];
    
    const traverse = (nodes, parentKeys = []) => {
      nodes.forEach(node => {
        // 检查当前节点是否匹配
        if (node.title.includes(searchText)) {
          matchedKeys.push(node.elementId);
          // 将当前节点的所有父节点加入展开列表
          expandKeys.push(...parentKeys);
        }
        
        // 递归遍历子节点
        if (node.children && node.children.length > 0) {
          traverse(node.children, [...parentKeys, node.elementId]);
        }
      });
    };
    
    traverse(treeNodes);
    // 去重并返回
    return [...new Set(expandKeys)];
  };

  const handleTreeCheck = (checkedKeys,event) => {
    console.log(event.checkedKeys);
    console.log(event.halfCheckedKeys);
    const data = {
      checked: checkedKeys,
      halfChecked: event.halfCheckedKeys
    };
    setCheckedKeys(data);
  };

  const handleTransferChange = (targetKeys) => {
    setRoleApi(targetKeys);
  };

  const handleCancel = () => {
    onCancel && onCancel();
  };

  // 保存元素权限
  const saveRoleElement = () => {
    
    const allCheckedKeys = [...new Set([...checkedKeys.checked, ...checkedKeys.halfChecked])];
    const idList = {
      id: roleId,
      list: allCheckedKeys
    };

    return saveRoleElements(idList).then(res => {
      if (res.code === '200') {
        message.success('页面元素权限保存成功');
        return true;
      }
      return false;
    });
  };

  // 保存接口权限
  const saveRoleApi = () => {
    const idList = {
      id: roleId,
      list: roleApi
    };

    return saveRolePermission(idList).then(res => {
      if (res.code === '200') {
        message.success('接口权限保存成功');
        return true;
      }
      return false;
    });
  };

  const handleConfirm = async () => {
    let result = false;
    if (activeTab === 'elements') {
      result = await saveRoleElement();
    } else if (activeTab === 'api') {
      result = await saveRoleApi();
    }

    if (result) {
      onConfirm && onConfirm();
    }
  };

  const filterTreeNode = (node) => {
    if (!filterText) return true;
    return node.title.includes(filterText);
  };

  // 根据选中的叶子节点计算全选和半选状态
  const calculateCheckedState = (checkedLeafIds, treeNodes) => {
    const checked = [];
    const halfChecked = [];
    
    const calculateNodeState = (nodes) => {
      const result = [];
      nodes.forEach(node => {
        if (node.children && node.children.length > 0) {
          const childStates = calculateNodeState(node.children);

          const allChecked = childStates.every(state => state === 'checked');
          const someChecked = childStates.some(state => state === 'checked' || state === 'halfChecked');
          
          if (allChecked) {
            checked.push(node.elementId);
            result.push('checked');
          } else if (someChecked) {
            halfChecked.push(node.elementId);
            result.push('halfChecked');
          } else {
            result.push('unchecked');
          }
        } else {
          if (checkedLeafIds.includes(node.elementId)) {
            checked.push(node.elementId);
            result.push('checked');
          } else {
            result.push('unchecked');
          }
        }
      });
      return result;
    };
    
    calculateNodeState(treeNodes);
    
    return { checked: [...new Set(checked)], halfChecked: [...new Set(halfChecked)] };
  };

  // 使用 items 属性替代已弃用的 TabPane
  const tabItems = [
    {
      label: '页面元素权限',
      key: 'elements',
      children: (
        <>
          <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16 }}>
            <Search
              placeholder="请输入元素名称"
              value={filterText}
              onChange={handleSearch}
              style={{ width: 240 }}
            />
          </div>
          <div style={{ maxHeight: 400, overflowY: 'auto' }}>
            <Tree
              treeData={treeData}
              checkedKeys={checkedKeys}
              onCheck={handleTreeCheck}
              checkable
              expandedKeys={expandedKeys}
              autoExpandParent={autoExpandParent}
              onExpand={(expandedKeys) => {
                setExpandedKeys(expandedKeys);
                setAutoExpandParent(false);
              }}
              filterTreeNode={filterTreeNode}
              fieldNames={{ title: 'title', key: 'elementId', children: 'children' }}
            />
          </div>
        </>
      ),
    },
    {
      label: '接口权限',
      key: 'api',
      children: (
        <Transfer
          dataSource={allApi}
          targetKeys={roleApi}
          onChange={handleTransferChange}
          render={item => item.title}
          showSearch
          listStyle={{ width: '100%', height: 400 }}
          titles={['接口', '用户接口权限']}
          filterOption={(inputValue, item) =>
            item.title.toLowerCase().indexOf(inputValue.toLowerCase()) !== -1
          }
        />
      ),
    },
  ];

  return (
    <Modal
      title="权限配置"
      open={visible}
      onCancel={handleCancel}
      onOk={handleConfirm}
      width={800}
    >
      <Tabs activeKey={activeTab} onChange={handleTabChange} items={tabItems} />
    </Modal>
  );
};

export default RolePermissionConfig;